package org.example.partner.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import org.example.contract.domain.Contract;
import org.example.contract.mapper.ContractMapper;
import org.example.partner.domain.Partner;
import org.example.partner.domain.TenementInfo;
import org.example.utils.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.partner.mapper.DeptMapper;
import org.example.partner.domain.Dept;
import org.example.partner.service.IDeptService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 合作伙伴1Service业务层处理
 *
 * @author 小孟微信：xiaomengcode
 * @date 2024-06-12
 */
@Service
public class DeptServiceImpl implements IDeptService
{
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private ContractMapper contractMapper;


    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 查询合作伙伴1
     *
     * @param deptId 合作伙伴1主键
     * @return 合作伙伴1
     */
    @Override
    public Dept selectDeptByDeptId(Long deptId)
    {
        return deptMapper.selectDeptByDeptId(deptId);
    }

    /**
     * 查询合作伙伴1列表
     *
     * @param dept 合作伙伴1
     * @return 合作伙伴1
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Dept> selectDeptList(Dept dept)
    {
        return deptMapper.selectDeptList(dept);
    }

    @Override
    public int insertDept(Dept dept){
        dept.setParentId(100L);
        dept.setAncestors("100,0");
        dept.setCreateBy(ShiroUtils.getUserId()+"");
        dept.setCreateTime(DateUtils.getNowDate());
       return deptMapper.insertDept(dept);
    }
    /**
     * 新增合作伙伴1
     *
     * @param dept 合作伙伴1
     * @return 结果
     */
    @Override
    @Transactional
    public int register(Dept dept)
    {

        //判断是否存在企业名称
        Dept dept1=new Dept();
        dept1.setDeptName(dept.getDeptName());
        List<Dept> partners = deptMapper.selectDeptList(dept1);
        if(partners !=null && partners.size()>0){
            throw new ServiceException("已存在："+dept1.getDeptName());
        }
        //判断是否存在企业税号
        Dept dept2=new Dept();
        dept2.setCode(dept.getCode());
        List<Dept> partners2 = deptMapper.selectDeptList(dept2);
        if(partners2 !=null && partners2.size()>0){
            throw new ServiceException("已存在："+dept2.getCode());
        }

        //判断是否存在手机号
        SysUser sysUser = userMapper.checkPhoneUnique(dept.getPhone());
        if(sysUser !=null){
            throw new ServiceException("已存在："+dept.getPhone());
        }
        SysUser sysUser2 = userMapper.checkLoginNameUnique(dept.getLoginName());
        if(sysUser2 !=null){
            throw new ServiceException("已存在："+dept.getLoginName());
        }
        int count=0;
        dept.setParentId(100L);
        dept.setAncestors("0,100");
        dept.setCreateBy(1+"");
        dept.setCreateTime(DateUtils.getNowDate());
        deptMapper.insertDept(dept);


        //初始化登录用户账号
        SysUser user=new SysUser();
        user.setUserName(dept.getDeptName());
        user.setSalt(ShiroUtils.randomSalt());
        user.setLoginName(dept.getLoginName());
        user.setPhonenumber(dept.getPhone());
        user.setPassword(passwordService.encryptPassword(dept.getLoginName(), dept.getPassword(), user.getSalt()));
        user.setDeptId(dept.getDeptId());
        count= userMapper.insertUser(user);

        //角色
        insertUserRole(user.getUserId(), new Long[]{Util.SUPPLIER_ROLE});

        return count;
    }
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotNull(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 修改合作伙伴1
     *
     * @param dept 合作伙伴1
     * @return 结果
     */
    @Override
    public int updateDept(Dept dept)
    {
        dept.setUpdateTime(DateUtils.getNowDate());
        return deptMapper.updateDept(dept);
    }

    /**
     * 批量删除合作伙伴1
     *
     * @param deptIds 需要删除的合作伙伴1主键
     * @return 结果
     */
    @Override
    public int deleteDeptByDeptIds(String deptIds)
    {
        return deptMapper.deleteDeptByDeptIds(Convert.toStrArray(deptIds));
    }

    /**
     * 删除合作伙伴1信息
     *
     * @param deptId 合作伙伴1主键
     * @return 结果
     */
    @Override
    public int deleteDeptByDeptId(Long deptId)
    {
        Contract contract = new Contract();
        contract.setBuyDeptId(deptId);
        contract.setOwnerDeptId(deptId);
        List<Contract> contracts = contractMapper.selectPartnerContractList(contract);
        if(contracts.size()>0){
            throw new ServiceException("已经存在合同关系，不能删除");
        }
        return deptMapper.deleteDeptByDeptId(deptId);
    }


    @Override
    public List<Ztree> selectDeptTree(Dept dept)
    {
        List<Dept> deptList=null;
        if (Util.isZuHuRole()){
            dept.setDeptId(ShiroUtils.getSysUser().getDeptId());
            deptList = deptMapper.selectDeptTreeList(dept);
        }else{
            deptList=deptMapper.selectDeptList(dept);
        }

        List<Ztree> ztrees = initZtree(deptList,null);
        return ztrees;
    }

    public List<Ztree> initZtree(List<Dept> deptList, List<String> roleDeptList)
    {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (Dept dept : deptList)
        {
            if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
            {
                Ztree ztree = new Ztree();
                ztree.setId(dept.getDeptId());
                ztree.setpId(dept.getParentId());
                ztree.setName(dept.getDeptName());
                ztree.setTitle(dept.getDeptName());
                if (isCheck)
                {
                    ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

}
